import React, { PropTypes, Component } from 'react';
import Table from './MyTable'
import Column from './Column'
import { myAjax, ROOTURL_TABLE } from './../publicAPI/publicAPI';
import styles from './SimpleTable.css';

export default React.createClass({
  getInitialState: function() {
    let date = new Date();
    return {
      year: date.getFullYear(),
      tData: [{}],
      hasClicked: true
    };
  },
  componentWillMount: function() {
    //this.getData();
    let _this = this;
    myAjax(ROOTURL_TABLE + '/cafune/wallet/depositmonsum.api', 'POST', {year:this.state.year}, function(data) {
      //console.log(data);
      let processData = [];
      let a = {'yearDepositSum': data.yearDepositSum};
      let b = data['walletMonDepositSum'];
      Object.assign(b,a);
	    processData.push(b);
      //console.log(processData);
      this.setState({
      	tData: processData
      });
      this.setState({tData: processData});
    }.bind(_this), function(err) {});
  },
  handleClick: function() {
    let yearSelect = parseInt(this.refs.yearSelect.value);
    //console.log(yearSelect);
    if(!yearSelect || !(/^2\d{3}$/.test(yearSelect))) {
      alert("内容不能为空或格式错误");
      this.refs.yearSelect.focus();
      return
    }
    let _this = this;
    myAjax(ROOTURL_TABLE + '/cafune/wallet/depositmonsum.api', 'POST', {year:yearSelect}, function(data) {
      //console.log(data);
      let processData = [];
      let a = {'yearDepositSum': data.yearDepositSum};
      let b = data['walletMonDepositSum'];
      Object.assign(b,a);
      processData.push(b);
      //console.log(processData);
      this.setState({
        tData: processData
      });
      this.setState({tData: processData});
    }.bind(_this), function(err) {alert("获取服务器内容失败")});
  },
  handleKeyPress: function(e) {
    if(e.which == 13) {
      this.handleClick();
    }
  },
  render: function() {
    return (
      <div>
        <div>
          <label><input ref="yearSelect" onKeyPress={this.handleKeyPress} className={styles.input} placeholder="如：2016" />年</label>
          <button onClick={this.handleClick} className={styles.button}>确定</button>
        </div>
        <div>
        <Table data={this.state.tData} className={styles.container} needSum="false">          
          { 
            Object.keys(this.state.tData[0]).map(entry => {
              if(/\d/.test(entry)) {
                return <Column dataKey={entry} name={`${entry}月`} width="120px" key={`col-${entry}`}/>
              }             
            })
          }
          <Column dataKey='yearDepositSum' name='年充值总额' width="200px" key={`col-yearDepositSum`}/>
        </Table>
        </div>
      </div>
    );
  }
});
